package com.stiff.search.mq.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stiff.search.pojo.Item;
import com.stiff.search.service.ItemService;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.springframework.beans.factory.annotation.Autowired;

public class ItemMQHandler {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private HttpSolrServer httpSolrServer;
    @Autowired
    private ItemService itemService;
    public void execute(String msg){
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            Long id = jsonNode.get("itemId").asLong();
            String type = jsonNode.get("type").asText();
            if(StringUtils.equals(type,"insert")||StringUtils.equals(type,"update")){
                Item item = this.itemService.queryItemById(id);
                if(item!=null){
                    this.httpSolrServer.addBean(item);
                    this.httpSolrServer.commit();
                }
            }else if(StringUtils.equals(type,"detele")){
                this.httpSolrServer.deleteById(String.valueOf(id));
                this.httpSolrServer.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
